#!/bin/python

import requests
from sqlalchemy import Column, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.sqltypes import Integer

"""根据年份获取日期信息"""

# 创建对象的基类:
Base = declarative_base()


class Days(Base):
    # 表的名字:
    __tablename__ = 'lagou_days'

    # 表的结构:
    year = Column(Integer)
    month = Column(Integer)
    date = Column(Integer, primary_key=True)
    week = Column(Integer)
    workday = Column(Integer)
    week_cn = Column(String())
    holiday = Column(Integer)
    holiday_cn = Column(String())
    yearweek = Column(Integer)
    holiday_legal = Column(Integer)


# 初始化数据库连接:
engine = create_engine(
    'mysql+mysqlconnector://hive:12345678@linux123:3306/ebiz')
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
# 创建Session:
# session = DBSession()
# 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
# user = session.query(Days).one()


if __name__ == "__main__":

    # 创建session对象:
    session = DBSession()

    for i in range(1, 13):
        resp = requests.get(
            "https://api.apihubs.cn/holiday/get?field=year,month,date,week,weekend,workday,holiday,yearweek&year=2020&week=1,2,3,4,5,6,7&cn=1&size=31&page={}".format(i)).json()
        print(resp)

        days = resp["data"]["list"]

        for day in days:
            # print(day)
            try:
                days = Days()
                days.year = day["year"]
                days.month = day["month"]
                days.date = day["date"]
                days.week = day["week"]
                days.workday = day["workday"]
                days.week_cn = day["week_cn"]
                days.holiday = day["holiday"]
                days.holiday_cn = day["holiday_cn"]
                days.yearweek = day["yearweek"]
                if days.holiday in [22,11,44,55,66,88]:
                    days.holiday_legal = True
                else:
                    days.holiday_legal = False

                session.add(days)
                session.commit()
            except Exception as e:
                print(e)

    session.close()
